﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Controls;

namespace Sector7.Restaurant.Utility
{
    /// <summary>
    /// 可视化树工具类
    /// </summary>
    public static class VisualTreeUtil
    {
        /// <summary>
        /// 根据名称查找第一个匹配的子可视对象
        /// </summary>
        /// <typeparam name="T">子可视对象类型</typeparam>
        /// <param name="reference">父可视对象</param>
        /// <returns></returns>
        public static T FindChild<T>(DependencyObject reference) where T : FrameworkElement
        {
            T child = null;

            DependencyObject tempChild = null;
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(reference); ++i)
            {
                tempChild = VisualTreeHelper.GetChild(reference, i);

                if (tempChild is T && tempChild != null)
                {
                    child = tempChild as T;
                    break;
                }
                else
                {
                    tempChild = FindChild<T>(tempChild);

                    if (tempChild != null)
                    {
                        child = tempChild as T;
                        break;
                    }
                }
            }

            return child;
        }

        /// <summary>
        /// 根据名称查找所有子可视对象
        /// </summary>
        /// <typeparam name="T">子可视对象类型</typeparam>
        /// <param name="reference">父可视对象</param>
        /// <param name="childName">子可视对象名称</param>
        /// <returns></returns>
        public static List<T> FindAllChildren<T>(DependencyObject reference, string childName) where T : FrameworkElement
        {
            List<T> children = new List<T>();

            DependencyObject tempChild = null;
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(reference); ++i)
            {
                tempChild = VisualTreeHelper.GetChild(reference, i);

                if (tempChild is T && ((tempChild as T).Name == childName || string.IsNullOrEmpty(childName)))
                {
                    children.Add(tempChild as T);
                }
                else
                {
                    children.AddRange(FindAllChildren<T>(tempChild, childName));
                }
            }

            return children;
        }

        public static List<T> FindAllChildren<T>(ItemCollection items, string childName) where T : FrameworkElement
        {
            List<T> children = new List<T>();

            foreach (DependencyObject item in items)
            {
                children.AddRange(FindAllChildren<T>(item, childName));
            }

            return children;
        }
    }
}
